<?php

namespace app\admin\controller;

use app\admin\common\Constants;
use app\admin\model\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Seal extends \app\admin\controller\Backend
{
    protected $model = null;
    private $searchFields = ['name', 'status'];


    private $configModel = null;

    protected $needSelectCompany = true;
    protected $beforeActionList = [
        'getCurrentCompany',
        'permitNew' => ['only' => 'save'],
    ];

    public function _initialize()
    {
        $this->model = new \app\admin\model\Seal();
        parent::_initialize();
        $this->configModel = new Config();
    }

    /**
     * 更换设备
     */
    public function replaceDevice($oldId = null)
    {
        $oldId = $this->request->param('oldId');
        $row = $this->model
            ->with(['cover'])
            ->where("company_id", $this->company->id)
            ->where("id", $oldId)->find($oldId);
        if (!$row) {
            $this->error('记录不存在');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $this->checkToken();
            if ($params) {
                $currentUserId = $this->getCurrentUser();
                $company = $this->company;
                $params['date_received'] = strtotime($this->request->param('date_received'));
                $params['expired_time'] = strtotime($this->request->param('expired_time'));
                $params['updater'] = $currentUserId;
                $params["update_time"] = time();
                $params["department"] = join(",", $params["department"]);
                $params['company_id'] = $company['id'];
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                    $this->success("更换成功", url("index"));
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("成功");
                } else {
                    $this->error('未更新');
                }
            }
            $this->error('Parameter %s can not be empty');
        }
        $department = \app\admin\model\Department::where(["company_id" => $this->company->id])->select();
        $this->assign('companyIds', explode(",", $row->department));
        $this->assign('departments', $department);
        $sealTypes = $this->configModel->getSealTypes();
        $sealStatus = $this->configModel->getSealStatus();
        $this->assign('sealTypes', $sealTypes);
        $this->assign('sealStatuses', $sealStatus);
        $this->assign('__token__', $this->request->token());
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 屏蔽创建印章方法
     * @return mixed|void
     */
    public function create()
    {
        $this->notFound();
    }

    /**
     * 屏蔽删除印章方法
     * @param null $id
     * @return mixed|void
     */
    public function add($id = null)
    {
        $this->notFound();
    }

    public function edit($id = null)
    {
        $row = $this->model->with(['cover'])->where('id', $id)->find();
        if (!$row) {
            $this->error('记录不存在');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $this->checkToken();
            if ($params) {
                $currentUserId = $this->getCurrentUser();
                $company = $this->getCurrentCompany();
                $params['date_received'] = strtotime($this->request->param('date_received'));
                $params['expired_time'] = strtotime($this->request->param('expired_time'));
                $params['updater'] = $currentUserId;
                $params["update_time"] = time();
                $params["department"] = join(",", $params["department"]);
                $params['company_id'] = $company['id'];
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                    if ($this->request->isAjax()) {
                        $this->success("更新成功", url("index"));
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("成功");
                } else {
                    $this->error('未更新');
                }
            }
            $this->error('Parameter %s can not be empty');
        }
        $department = \app\admin\model\Department::where(["company_id" => $this->getCurrentCompany()->id])->select();
        $this->assign('companyIds', explode(",", $row->department));
        $this->assign('departments', $department);
        $sealTypes = $this->configModel->getSealTypes();
        $sealStatus = $this->configModel->getSealStatus();
        $this->assign('sealTypes', $sealTypes);
        $this->assign('sealStatuses', $sealStatus);
        $this->assign('__token__', $this->request->token());
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function index()
    {

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        if ($this->request->param('name')) {
            $where ['name'] = ['like', '%' . $this->request->param('name') . '%'];
        }
        if ($this->request->param('number')) {
            //$where ['number'] = ['eq', $this->request->param('number')];
            $where ['number'] = ['like', '%' . $this->request->param('number') . '%'];
        }
        if ($this->request->param('seal_type')) {
            $where ['seal_type'] = ['eq', $this->request->param('seal_type')];
        }
        $where['company_id'] = $this->getCurrentCompany()->id;
        $where['is_del'] = array('eq', 0);
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate(10);
        //echo  '<pre>';print_r($list);die;
        $configModel = new Config();
        $this->assign('sealTypes', $configModel->getConfigCacheByName(Constants::$SEAL_TYPE_KEY));
        $this->assign('sealStatuses', $configModel->getConfigCacheByName(Constants::$SEAL_STATUS_KEY));
        $this->assign('list', $list);
        $value = $this->request->param();
        $this->assign('params', $value);
        $company_id = $this->getCurrentCompany()->id;
        $time = db('company_introduction')->where(['id' => $company_id])->value('service_expiration_time');
        $dq_time = date('Y-m-d', $time);
        $this->assign('dq_time', $dq_time);
        return $this->fetch('index');
    }

    public function dc()
    {
        $company = $this->company;
        $company_id = $company->id;
        $where['company_id'] = $company_id;
        //print_r($company_id);die;

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model->with(['creatorUser', 'updaterUser', 'cover'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        vendor('phpexcel/PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //exit($objPHPExcel);
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '设备编号')
            ->setCellValue('B1', '印章名称')
            ->setCellValue('C1', '印章类型')
            ->setCellValue('D1', '收到日期')
            ->setCellValue('E1', '过期日期')
            ->setCellValue('F1', '备注')
            ->setCellValue('G1', '状态');

        //设置A列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);


        for ($i = 0; $i < count($list); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['number']);           //ID
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['name']);             //标签码
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['seal_type_txt']);    //防伪码
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['date_received_txt']);//ID
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['expired_time_txt']); //标签码
            $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['remark']);           //ID
            $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $list[$i]['status_txt']);       //标签码
        }
        //7.设置保存的Excel表格名称
        $filename = 'yz' . date('ymd', time()) . '.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('cs');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;


    }

    public function delete()
    {
        $id = input('id');
        $res = db('seal')->where(['id' => $id])->update(['is_del' => 1]);
        if ($res) {
            $this->success('成功');
        } else {
            $this->error('失败');
        }
    }
}